#include <stdio.h>
#include <string.h>

#define BUFFER_SIZE 100

/* 定义一个结构体变量表示个人信息 */
typedef struct Contact
{
    char name[BUFFER_SIZE];
    char phone[BUFFER_SIZE];
}Contact;

/* 定义一个包含联系人的数组 */
Contact contacts[BUFFER_SIZE];

/* 当前数组中已有联系人的个数 */
int numContacts = 0;

/* 添加联系人 */
void addContact()
{
    if (numContacts >= BUFFER_SIZE)
    {
        printf("通讯录已满\n");
        return;
    }

    Contact newContact;
    printf("请输入联系人姓名：");
    scanf("%s", newContact.name);

    printf("请输入联系人电话：");
    scanf("%s", newContact.phone);

    contacts[numContacts] = newContact;
    numContacts++;
}

/* 删除联系人 */
void delContact()
{
    if (numContacts == 0)
    {
        printf("通讯录为空\n");
        return;
    }

    char name[BUFFER_SIZE];
    printf("请输入要删除的联系人姓名：");
    scanf("%s", name);

    int temp = -1;
    for (int idx = 0; idx < numContacts; idx++)
    {
        if (contacts[idx].name, name == 0)
        {
            temp = idx;
            break;
        }
    }
    if (temp = -1)
    {
        printf("没有找到联系人\n");
        return;
    }

    for (int jdx = temp; jdx < numContacts - 1; jdx++)
    {
        contacts[jdx] = contacts[jdx + 1];
    }
    numContacts--;
    memset(&contacts[numContacts - 1], 0, sizeof(Contact));

    printf("联系人已成功删除\n");
}

/* 检查关键字是否在字符串中 */
int checkKeyWord(char *str, char *keyWord)
{
    int len1 = strlen(str);
    int len2 = strlen(keyWord);

    for (int idx = 0; idx <= len1; idx++)
    {
        int jdx;
        for (jdx = 0; jdx < len2; jdx++)
        {
            if (str[idx + jdx] != keyWord[jdx])
            break;
        }
        if (jdx == len2)
        {
            return 1;
        }
    }
    return 0;
}
/* 查找联系人 */
void searchContact()
{
    if (numContacts == 0)
    {
        printf("通讯录为空\n");
        return;
    }

    char keyWord[BUFFER_SIZE];
    printf("请输入要查找的关键字：");
    scanf("%s",keyWord);

    int count = 0;
    for (int pos = 0; pos < numContacts; pos++)
    {
        if (checkKeyWord(contacts[pos].name, keyWord) || checkKeyWord(contacts[pos].phone, keyWord))
        {
            printf("%s\t%s\n", contacts[pos].name, contacts[pos].phone);
            count++;
        }
    }

    if (count == 0)
    {
        printf("没有找到匹配的联系人\n");
    }
}

int main()
{
    int choice;

    do {
        printf("\n通讯录操作选项：\n");
        printf("1. 添加联系人\n");
        printf("2. 删除联系人\n");
        printf("3. 查找联系人\n");
        printf("4. 退出\n");
        printf("请选择操作：");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                addContact();
                break;
            case 2:
                delContact();
                break;
            case 3:
                searchContact();
                break;
            case 4:
                printf("退出程序\n");
                break;
            default:
                printf("无效选择，请重新选择\n");
        }
    } 
    while (choice != 4);

    return 0;
}
